﻿using Basic.FlowDAL;
using Basic.FlowModel;
using Basic.FlowModel.AuditCopyLog;
using Basic.FlowRemoteModel;
using WeDonekRpc.Helper;

namespace Basic.FlowCollect.lmpl
{
    internal class FlowAuditCopyLogCollect : IFlowAuditCopyLogCollect
    {
        private readonly IFlowAuditCopyLogDAL _BasicDAL;

        public FlowAuditCopyLogCollect(IFlowAuditCopyLogDAL basicDAL)
        {
            this._BasicDAL = basicDAL;
        }
        public Result Get<Result>(long id) where Result : class, new()
        {
            return this._BasicDAL.Get<Result>(id);
        }
        public AuditCopyDto[] Adds(long logId, AuditCopyLogAdd[] adds)
        {
            long[] empId = adds.Select(a => a.ToEmpId).ToArray();
            empId = _BasicDAL.Gets(a => a.LogId == logId && empId.Contains(a.ToEmpId), a => a.ToEmpId);
            if (!empId.IsNull())
            {
                if (empId.Length == adds.Length)
                {
                    return null;
                }
                adds = adds.Remove(a => empId.Contains(a.ToEmpId));
            }
            return this._BasicDAL.Adds(logId, adds);
        }
        public Dictionary<long, long[]> GetToEmpId(long[] itemId, FlowMsgType msgType)
        {
            if (itemId.IsNull())
            {
                return new Dictionary<long, long[]>();
            }
            return this._BasicDAL.Gets(a => itemId.Contains(a.ItemId) && a.MsgType == msgType && a.Status == FlowMsgStatus.待发送, a => new
            {
                a.ItemId,
                a.ToEmpId
            }).GroupBy(a => a.ItemId).ToDictionary(a => a.Key, a => a.Select(c => c.ToEmpId).ToArray());
        }
        public void SetStatus(AuditCopyStatus[] sets)
        {
            this._BasicDAL.SetStatus(sets);
        }
        public AuditCopyDto[] GetsCopyMsgs(long itemId, FlowMsgType msgType)
        {
            return this._BasicDAL.Gets<AuditCopyDto>(a => a.ItemId == itemId && a.MsgType == msgType && ConstDic.CopyWaitSendStatus.Contains(a.Status));
        }

        public long[] GetToVoidCopyId(long[] itemId)
        {
            return this._BasicDAL.Gets(a => itemId.Contains(a.ItemId) && a.Status == FlowMsgStatus.已发送, a => a.Id);
        }
    }
}
